package cn.nkjobsearch.html;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.nkjobsearch.config.Config;
import cn.nkjobsearch.config.ConfigChinaHR;
import cn.nkjobsearch.mysql.MysqlConn;
import cn.nkjobsearch.publicClass.File;

public class ComChinaHRSearchList extends Thread {
	private MysqlConn mysql = null;

	public ComChinaHRSearchList() {

	}

	/**
	 * 循环抓取ID
	 */
	public void run() {
		mysql = new MysqlConn();
		int cnt = 0;
		for (; ConfigChinaHR.CHINAHR_SEARCHLIST_P < ConfigChinaHR.CHINAHR_PROVINCE.length; ConfigChinaHR.CHINAHR_SEARCHLIST_P++) {
			for (; ConfigChinaHR.CHINAHR_SEARCHLIST_I < ConfigChinaHR.CHINAHR_INDUSTRY.length; ConfigChinaHR.CHINAHR_SEARCHLIST_I++) {
//				for (; ConfigChinaHR.CHINAHR_SEARCHLIST_C < ConfigChinaHR.CHINAHR_CATEGORY.length; ConfigChinaHR.CHINAHR_SEARCHLIST_C++) {
					ConfigChinaHR.CHINAHR_SEARCHLIST_C = 3;//只是取计算机类的职位
					getHTMLandPattern(ConfigChinaHR.CHINAHR_SEARCHLIST_P,
							ConfigChinaHR.CHINAHR_SEARCHLIST_I,
							ConfigChinaHR.CHINAHR_SEARCHLIST_C);
					System.out.print((++cnt) + " ");
					ConfigChinaHR.CHINAHR_SEARCHLIST_TIMER = 0;
//				}
//				ConfigChinaHR.CHINAHR_SEARCHLIST_C = 0;
			}
			ConfigChinaHR.CHINAHR_SEARCHLIST_I = 0;
		}
		ConfigChinaHR.CHINAHR_SEARCHLIST_P = 0;
		ConfigChinaHR.CHINAHR_SEARCHLIST_I = 0;
		ConfigChinaHR.CHINAHR_SEARCHLIST_C = 0;
		this.close();
		ConfigChinaHR.CHINAHR_SEARCHLIST_RUNNING = false;
	}

	/*
	 * close() 关闭数据库
	 */
	public void close() {
		if (mysql != null) {
			mysql.close();
		}
	}

	private void getHTMLandPattern(int provinceID, int industryID,
			int categoryID) {
		String searchURL = makeSearchListURL(provinceID, industryID, categoryID);
		boolean startPattern = false;
		char jsonResultChar[] = { 'j', 's', 'o', 'n' };
		boolean jsonResultBool[] = { false, false, false, false };
		int ch;
		InputStreamReader in = null;
		StringBuffer input = new StringBuffer();
		try {
			URL u = new URL(searchURL);
			in = new InputStreamReader(u.openStream(), "gb2312");
		} catch (Exception e) {
			if (Config.DEBUG_INFO) {
				e.printStackTrace();
			}
		}
		/**
		 * 为了减少后面的正则匹配的字符串的长度 此处仅仅匹配ChinaHR搜索列表界面的部分代码 即以“json”开头，以换行结尾的部分
		 */
		try {
			while ((ch = in.read()) != -1) {
				if (!startPattern) {
					if (!jsonResultBool[0]) {
						if ((char) ch == jsonResultChar[0]) {
							jsonResultBool[0] = true;
						}
					} else {
						if (!jsonResultBool[1]) {
							if ((char) ch == jsonResultChar[1]) {
								jsonResultBool[1] = true;
							} else {
								jsonResultBool[0] = false;
							}
						} else {
							if (!jsonResultBool[2]) {
								if ((char) ch == jsonResultChar[2]) {
									jsonResultBool[2] = true;
								} else {
									jsonResultBool[0] = false;
									jsonResultBool[1] = false;
								}
							} else {
								if (!jsonResultBool[3]) {
									if ((char) ch == jsonResultChar[3]) {
										jsonResultBool[3] = true;
									} else {
										jsonResultBool[0] = false;
										jsonResultBool[1] = false;
										jsonResultBool[2] = false;
									}
								} else {
									startPattern = true;
								}
							}
						}
					}
					continue;
				} else {
					if ((char) ch == '\n') {
						break;
					}
				}
				input.append((char) ch);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (input.length() < 100) {
			File.writeLog(ConfigChinaHR.CHINAHR_SEARCHLIST_LOG_PATH, provinceID
					+ "\t" + industryID + "\t" + categoryID + "\t0\t0");
			return;
		}
		String htmlContent = input.toString();
		Pattern patternJobID = Pattern.compile(
				"\"JobID\":[\\s]{1}\"[0-9]{20}\"", Pattern.CASE_INSENSITIVE);
		Matcher matcherJobID = patternJobID.matcher(htmlContent);
		List<String> matchJobID = new ArrayList<String>();
		for (; matcherJobID.find();) {
			matchJobID.add(htmlContent.substring(matcherJobID.start(),
					matcherJobID.end()).substring(10, 30));
		}

		List<String> matchJobDate = new ArrayList<String>();
		Pattern patternJobDate = Pattern.compile(
				"\"JobDate\":[\\s]{1}\"[0-9]{4}-[0-9]{2}-[0-9]{2}\"",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherJobDate = patternJobDate.matcher(htmlContent);
		for (; matcherJobDate.find();) {
			matchJobDate.add(htmlContent.substring(matcherJobDate.start(),
					matcherJobDate.end()).substring(12, 22));
		}

		if (matchJobID.size() != 0 && matchJobID.size() == matchJobDate.size()) {
			int writeDBCnt = 0;
			for (int k = 0; k < matchJobID.size(); k++) {
				if (writeChinaHRJobIDToDB(matchJobID.get(k), matchJobDate
						.get(k))) {
					writeDBCnt++;
				}
			}
			File.writeLog(ConfigChinaHR.CHINAHR_SEARCHLIST_LOG_PATH, provinceID + "\t"
					+ industryID + "\t" + categoryID + "\t" + writeDBCnt + "\t"
					+ matchJobID.size());
		} else {
			System.out
					.println("INFO: matchJobID.size() !=  matchJobDate.size()");
		}
	}

	/*
	 * 将ID和Date写进数据库，jobID是主键，返回boolean以便统计写入成功的次数
	 */
	private boolean writeChinaHRJobIDToDB(String jobID, String jobDate) {
		String sql = "INSERT INTO  `ChinaHRJobID` (  `jobID` ,  `jobDate` , `category`) "
				+ "VALUES ('"
				+ jobID
				+ "',  '"
				+ jobDate
				+ "', '"
				+ ConfigChinaHR.CHINAHR_CATEGORY[ConfigChinaHR.CHINAHR_SEARCHLIST_C]
				+ "');";
		if (mysql.executeInsert(sql)) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 按照规则合成的搜索URL
	 */
	private String makeSearchListURL(int provinceID, int industryID,
			int categoryID) {
		/*
		 * myLocIDList市 myLocParentIDList省 indIDList行业 jobPostCycle 发布时间
		 * occIDList职位子类别 occParentIDList职位父类别
		 */

		return "http://searchjob.chinahr.com/searchresult.html?occIDList="
				+ ConfigChinaHR.CHINAHR_CATEGORY[categoryID]
				+ "&occParentIDList="
				+ ConfigChinaHR.CHINAHR_CATEGORY[categoryID] + "&myLocIDList="
				+ ConfigChinaHR.CHINAHR_PROVINCE[provinceID]
				+ "&myLocParentIDList="
				+ ConfigChinaHR.CHINAHR_PROVINCE[provinceID] + "&indIDList="
				+ ConfigChinaHR.CHINAHR_INDUSTRY[industryID]
				+ "&companyTypeIDList=&jobPostCycle=90&isInterView=1";
	}
}
